package com.ztmg.common.util.HttpClientUtils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ztmg.common.util.aes.SymmetricEncoder;
import com.ztmg.common.util.handleSign.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    private final byte[] secretBytes = "MzVjZTgxZTQzMDUwNGNiMGExZWJkMWNh".getBytes();

    private final byte[] ivbytes = {(byte)'0',(byte)'0',(byte)'0',(byte)'0',(byte)'0',(byte)'0',(byte)'0',(byte)'0'};
    public static final String priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL9u/fhunnIFicQQd/dFKWtM+8tO+g/XQtBBzQI5h/3BqGTwvjQJaxqq+6dKxxLSR5QdU+fipiR9Nm7WbLkq9Aya3u2CT3X3bgBqT4LtKxXon5WE8RwtedMow1XD+T/OBvL4lcal5H0KHGvnKrxtzYHWhroYBMnD0Mnp6Ix6taQhAgMBAAECgYEArB0ztKhoRqXaDnCsG6KQMcv+WvW/+HwWsz1mAAkPzsPODisxJ4IMTObL6cZeo/pxpqaTqNnrfMUjKpYZHIaU8itbFqDF+6NdXUPgzppek6i+XtolaZJLsujaozcDXOXUmJeQAZmc/bTyym2mFQcE2tmnES99Tcxb1osM4FQxcpECQQD5q5KFualCVijI8asgIiBLxKHNXrnX9GustVB/9OfA8bb8HoC/ORHux1v+SJCCQvmthtTnw5DUYkHkyXG5KVLFAkEAxElys0wBAKI0KEj9qwvGToaAncSMeEOd2ea38gbJOWD+mq/YFTluQKev52vk5cj02ALilWjB61hTg+5xWD0xrQJAe6zR2AwwG/wyF9gevLwq4110CRdzV9ZrwBHQ3pGie6FA04MIo7DRgUaf+0ZWzy/+Hkc8D9KAW7SQj5R6EQ63QQJARypeBLWss18by/NSzT4SowvO++R0DXJue79Tt9NQB5asGMdib6eH2rcxZpVOwyUN6Hd7UTJPBJXcibvcqmJdbQJAA5iptviyGUQAou9tYSyL1/DB559u0CIBe/IEH7sgQZlEUNXdFdRlDN+CkMFzKc2VQdu9HQc5yXcatMHTuGy74g==";
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    /***
     *
     * @Title: convertStreamToString
     * @Description: 流转字符串
     *
     * @param istream
     * @return
     * @throws IOException
     * @return: String
     * @Author: yangshuai
     * @date: 2016年12月17日 下午3:43:48
     */
    public static String convertStreamToString(InputStream istream) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while (null != (line = reader.readLine()))
        {
            sb.append(line + "\n");
        }
        if (null != istream)
        {
            istream.close();
        }
        if (null != reader)
        {
            reader.close();
        }
        return sb.toString();
    }

    public static String getSignString(String data) throws Exception
    {
        //获取KeyFactory，指定RSA算法

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        //将BASE64编码的私钥字符串进行解码

        BASE64Decoder decoder = new BASE64Decoder();

        byte[] encodeByte = decoder.decodeBuffer(priKey);

//将BASE64解码后的字节数组，构造成PKCS8EncodedKeySpec对象，生成私钥对象
//        java.security.Security.addProvider(
//                new org.bouncycastle.jce.provider.BouncyCastleProvider()
//        );
        PrivateKey privatekey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodeByte));



        //b）使用私钥，对数据进行签名

        //获取Signature实例，指定签名算法（本例使用SHA1WithRSA）

        Signature signature = Signature.getInstance("SHA1WithRSA");

//加载私钥

        signature.initSign(privatekey);

//更新待签名的数据

        signature.update(data.getBytes("UTF-8"));

//进行签名

        byte[] signed = signature.sign();

//将加密后的字节数组，转换成BASE64编码的字符串，作为最终的签名数据

        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(signed);

    }
    public static void main(String args[])throws Exception {
//
//        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCRloa+hgeoulAfNwXSD45U0z7" +
//                "7gBe59Jtvf6bX2pJuCg5CO1r4DRtoatNaNCupxX9+CwPjcaJ6aEgaHpEWkYz0lTA" +
//                "f7m22ipmbWG5FK7ToqVTnkAKEtBYQrgTQpx0MaXXebPwFS28R/K6npD8B2UjWpes" +
//                "mv5kbkr3L8hd7ypnnwIDAQAB";
        //String url = "http://wwy.xjtu.edu.cn/api/wx.msg/refundmsg.html";

        String url = "http://122.224.250.35:7020/Parking/Handheld/GetCarCodes/";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("carCode","14");
//        jsonObject.put("password","123456");
//        jsonObject.put("member_id","56");
//        jsonObject.put("sn","2018061917592354389");
//        jsonObject.put("money","0.01");
//        jsonObject.put("type","deposit");
        String data = JSON.toJSONString(jsonObject);
//        System.out.println(data);
//        byte[] encrypt = SignatureUtil.signByPub(data.getBytes("utf-8"),Base64.decode(publicKey),"RSA");
//        String params= "data="+URLEncoder.encode(Base64.encode(encrypt), "UTF-8");
         data = SymmetricEncoder.AESEncode(Base64.decode("cmVmb3JtZXJyZWZvcm1lcg=="),data);
        System.out.println(data);
        String result = sendPost(url,data);
        System.out.println(result);
        System.out.println(SymmetricEncoder.AESDncode( Base64.decode("cmVmb3JtZXJyZWZvcm1lcg=="),result));
    }
    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    /**
     * 初始向量的方
     * @return
     * @throws GeneralSecurityException
     */
    private static byte[] initIv(){

        byte[] iv = new byte[8];
        for (int i = 0; i < 8; ++i) {
            iv[i] = 0;
        }
        return iv;
    }
}
